package com.example.fengyungo_user.utils;

import static android.content.Context.MODE_PRIVATE;

import android.app.Service;
import android.content.SharedPreferences;

import androidx.fragment.app.FragmentActivity;

import com.example.fengyungo_user.constant.MessageConstant;
import com.example.fengyungo_user.constant.ResultConstant;
import com.example.fengyungo_user.constant.UserConstant;
import com.example.fengyungo_user.domain.Message;
import com.example.fengyungo_user.domain.MessageList;
import com.example.fengyungo_user.domain.User;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class UserUtils {

    /**
     * 处理来自后端的Driver响应数据，结果存到List中
     *
     * @param jsonData String
     * @return List<MessageList>
     */
    public static List<User> parseUsersJsonWithJsonObject(String jsonData) {
        List<User> users = null;
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            JSONArray jsonArray = jsonObject.getJSONArray(ResultConstant.DATA);
            users = parseUserWithJsonArray(jsonArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return users;
    }

    /**
     * 将jsonArray中的json数据封装到Users对象中
     * @param jsonArray JSONArray
     * @return List<User>
     * @throws JSONException JSONException
     */
    private static List<User> parseUserWithJsonArray(JSONArray jsonArray) throws JSONException {
        ArrayList<User> users = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject userJson = jsonArray.getJSONObject(i);
            User user = new User();

            String id = userJson.getString(UserConstant.ID);
            String username = userJson.getString(UserConstant.USERNAME);
            String sex = userJson.getString(UserConstant.SEX);
            String phone = userJson.getString(UserConstant.PHONE);
            String password = userJson.getString(UserConstant.PASSWORD);
            String idCard = userJson.getString(UserConstant.ID_CARD);
            String avatar = userJson.getString(UserConstant.AVATAR);
            String status = userJson.getString(UserConstant.STATUS);
            String createTime = userJson.getString(UserConstant.CREATE_TIME);
            String nickname = userJson.getString(UserConstant.NICKNAME);
            String mail = userJson.getString(UserConstant.MAIL);

            user.setUserId(id);
            user.setUserUsername(username);
            user.setUserSex(sex);
            user.setUserPhone(phone);
            user.setUserPassword(password);
            user.setUserIdCard(idCard);
            user.setUserAvatar(avatar);
            user.setUserStatus(Integer.parseInt(status));
            user.setUserCreateTime(createTime);
            user.setUserNickname(nickname);
            user.setUserMail(mail);

            users.add(user);
        }
        return users;
    }

    /**
     * 处理来自后端的MessageList响应数据，结果存到List中
     *
     * @param jsonData String
     * @return List<MessageList>
     */
    public static List<MessageList> parseMessageListJsonWithJsonObject(String jsonData) {
        List<MessageList> messageLists = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            JSONArray jsonArray = jsonObject.getJSONArray(ResultConstant.DATA);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject messageListJson = jsonArray.getJSONObject(i);
                MessageList messageList = new MessageList();

                String listId = messageListJson.getString(MessageConstant.LIST_ID);
                String driverId = messageListJson.getString(MessageConstant.DRIVER_ID);
                String userId = messageListJson.getString(MessageConstant.USER_ID);
                String driverNickname = messageListJson.getString(MessageConstant.DRIVER_NICKNAME);
                String driverAvatar = messageListJson.getString(MessageConstant.DRIVER_AVATAR);
                int driverOnline = messageListJson.getInt(MessageConstant.DRIVER_ONLINE);
                int userUnread = messageListJson.getInt(MessageConstant.USER_UNREAD);
                String lastContent = messageListJson.getString(MessageConstant.LAST_CONTENT);
                String lastTime = messageListJson.getString(MessageConstant.LAST_TIME);
                int userListStatus = messageListJson.getInt(MessageConstant.USER_LIST_STATUS);

                messageList.setListId(listId);
                messageList.setDriverId(driverId);
                messageList.setUserId(userId);
                messageList.setDriverNickname(driverNickname);
                messageList.setDriverAvatar(driverAvatar);
                messageList.setDriverOnline(driverOnline);
                messageList.setUserUnread(userUnread);
                messageList.setLastContent(lastContent);
                messageList.setLastTime(lastTime.substring(5, 10));
                messageList.setUserListStatus(userListStatus);

                messageLists.add(messageList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messageLists;
    }

    /**
     * 在FragmentActivity获取当前用户的信息
     *
     * @return Driver
     */
    public static User getUserInfo(FragmentActivity fragmentActivity) {
        // 从SharedPreferences中获取信息
        SharedPreferences preferences = fragmentActivity.getSharedPreferences(UserConstant.SP_NAME, MODE_PRIVATE);

        User user = parseUser(preferences);

        return user;
    }

    /**
     * 从SharedPreferences中获取用户信息
     * @param preferences SharedPreferences
     * @return User
     */
    private static User parseUser(SharedPreferences preferences) {
        String id = preferences.getString(UserConstant.ID, "");
        String avatar = preferences.getString(UserConstant.AVATAR, "");
        String nickname = preferences.getString(UserConstant.NICKNAME, "未设置");
        String username = preferences.getString(UserConstant.USERNAME, "123456");
        String sex = preferences.getString(UserConstant.SEX, "未设置");
        String phone = preferences.getString(UserConstant.PHONE, "未设置");
        String mail = preferences.getString(UserConstant.MAIL, "未设置");
        String password = preferences.getString(UserConstant.PASSWORD, "");
        Integer status = preferences.getInt(UserConstant.STATUS, 0);
        String createTime = preferences.getString(UserConstant.CREATE_TIME, "");
        String idCard = preferences.getString(UserConstant.ID_CARD, "");

        User user = new User();
        user.setUserId(id);
        user.setUserNickname(nickname);
        user.setUserUsername(username);
        user.setUserSex(sex);
        user.setUserPhone(phone);
        user.setUserPassword(password);
        user.setUserIdCard(idCard);
        user.setUserAvatar(avatar);
        user.setUserStatus(status);
        user.setUserCreateTime(createTime);
        user.setUserMail(mail);

        return user;
    }

    /**
     * 在服务中获取当前用户的信息
     * @param service Service
     * @return Driver
     */
    public static User getUserInfoInService(Service service) {
        // 从SharedPreferences中获取信息
        SharedPreferences preferences = service.getSharedPreferences(ResultConstant.DATA, MODE_PRIVATE);

        User user = parseUser(preferences);

        return user;
    }

    /**
     * 处理来自后端的Message响应数据，结果存到List中
     *
     * @param jsonData String
     * @return List<Message>
     */
    public static List<Message> parseMessageJsonWithJsonObject(String jsonData) {
        List<Message> messages = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(jsonData);
            JSONArray jsonArray = jsonObject.getJSONArray(ResultConstant.DATA);
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject messageJson = jsonArray.getJSONObject(i);
                Message message = new Message();

                String messageId = messageJson.getString(MessageConstant.MESSAGE_ID);
                String senderId = messageJson.getString(MessageConstant.SENDER_ID);
                String receiverId = messageJson.getString(MessageConstant.RECEIVER_ID);
                String content = messageJson.getString(MessageConstant.CONTENT);
                String sendTime = messageJson.getString(MessageConstant.SEND_TIME);

                message.setMessageId(messageId);
                message.setSenderId(senderId);
                message.setReceiverId(receiverId);
                message.setContent(content);
                message.setSendTime(sendTime);

                messages.add(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return messages;
    }
}
